package webEquipeRechercheGwt.client.entityShowingPanel.linkCreationPanel.person;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import webEquipeRechercheGwt.client.callback.consultation.CallBackGetAllPaper;
import webEquipeRechercheGwt.client.callback.consultation.commands.CommandGetAllPapersImplToPaperLinkPanel;
import webEquipeRechercheGwt.client.entityMirror.PaperMirror;
import webEquipeRechercheGwt.client.entityShowingPanel.PersonPanel;
import webEquipeRechercheGwt.client.entityShowingPanel.linkCreationPanel.ToPaperLinkCreationPanel;
import webEquipeRechercheGwt.client.handler.creation.link.person.ClickHandlerPersonToPaperLink;
import webEquipeRechercheGwt.client.services.PaperService;
import webEquipeRechercheGwt.client.services.PaperServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;

public class PersonToPaperLinkCreationPanel extends HorizontalPanel implements
		ToPaperLinkCreationPanel {

	private PersonPanel origine;
	private List<PaperMirror> papers;
	private ListBox listBox;
	private Button validation;
	
	public PersonToPaperLinkCreationPanel(PersonPanel origine){
		super();
		this.origine = origine;
		papers = new ArrayList<PaperMirror>();
		listBox = new ListBox();
		listBox.setVisibleItemCount(1);
		validation = new Button("Create link");
		validation.addClickHandler(new ClickHandlerPersonToPaperLink(papers, listBox, origine.getMirror(), origine.getMainPanel()));
	}
	
	private void loadAllPersons(){
		PaperServiceAsync service = GWT.create(PaperService.class);
		AsyncCallback<Collection<PaperMirror>> callback = new CallBackGetAllPaper(new CommandGetAllPapersImplToPaperLinkPanel(this));
		service.getPapers(callback);
	}
	
	public void setPapers(Collection<PaperMirror> result){
		papers.clear();
		papers.addAll(result);
		papers.removeAll(origine.getMirror().getPapers());
		updateSelection();
	}
	
	private void updateSelection(){
		listBox.clear();
		for(PaperMirror p : papers){
			listBox.addItem(p.getTitle());
		}
	}

	@Override
	protected void onLoad() {
		super.onLoad();
		add(listBox);
		add(validation);
		loadAllPersons();
	}

}
